import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Button,
  Checkbox,
  Input,
  Select,
  Modal,
  Pagination,
  Tooltip,
} from 'antd';

import styles from './index.less';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;

interface GoodsProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  INITINFO: any;
  detailInfo: any;
  location: { query: any };
}

interface GoodsState {
  dataBaseList: any;
  pageIndex: number;
  pageSize: number;
  visible: boolean;
  pliesNumber: any[];
  selectItem: {
    index: number;
    idValue: string;
    name: string;
  };
}

@connect(({
  goodsManagementAdd: { detailInfo },
  common: { INITINFO },
}: any) => ({
  detailInfo,
  INITINFO,
}))

class GoodsElement extends React.Component<GoodsProps, GoodsState> {
  constructor(props: GoodsProps) {
    super(props);
    const pliesNumber = Array.from(Array(99), (v, k) => k + 1);
    this.state = {
      dataBaseList: this.letterOutput(),
      pliesNumber,
      pageIndex: 1,
      pageSize: 15,
      visible: false,
      selectItem: {
        index: 0,
        idValue: '',
        name: '',
      },
    };
  }

  componentDidMount() {
    // 获取套餐类型
    this.fetchAction('common/fetchTariffList');
    const {
      location: { query: { id } },
    } = this.props;

    // 查看信息
    if (id) {
      this.fetchAction('fetch', {
        logisId: id,
        pageIndex: 1,
        pageSize: 702,
      });
    }
  }

  componentDidUpdate(prevProps: any) {
    const {
      detailInfo,
      location: { query: { id } },
    } = this.props;

    if (!_.isEqual(detailInfo, prevProps.detailInfo)
        || id !== prevProps.location.query.id
    ) {
      this.fetchAction('fetch', {
        logisId: id,
        pageIndex: 1,
        pageSize: 702,
      });
      this.mergingData();
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `goodsManagementAdd/${typeName}`;
    dispatch({ type, payload });
  };

  // 查看原有数据,并融合大数据，进行展示
  mergingData = () => {
    const dataBaseList = this.letterOutput();
    const { detailInfo: { list } } = this.props;

    if (list !== undefined) {
      list.forEach((item: any) => {
        dataBaseList.forEach((itemBase: any) => {
          Object.keys(itemBase).forEach((key: string) => {
            if (item.code === key) {
              itemBase[key] = Object.assign(
                {},
                {
                  id: item.id,
                  name: item.name,
                  layers: item.layers,
                  tariffpkgId: item.tariffpkgId,
                  status: true,
                },
              );
            }
          });
        });
      });
    }

    this.setState({ dataBaseList });
  };

  // 循环出702条数据
  letterOutput = () => {
    const chars = [];

    for (let i = 0; i < 26; i += 1) {
      chars[i] = String.fromCharCode(i + 65);
    }

    for (let i = 0; i < 26; i += 1) {
      for (let j = 0; j < 26; j += 1) {
        chars.push(chars[i] + chars[j]);
      }
    }

    const goodsList: any = [];
    const charsArr = [];

    for (let i = 0; i < chars.length;) {
      charsArr.push(chars.slice(i, (i += 4)));
    }

    charsArr.forEach((item: any) => {
      const newObj = {};
      item.forEach((itemChild: any) => {
        newObj[itemChild] = {
          name: '', // 货架地址
          layers: '', // 层数
          tariffpkgId: 0, // 套餐
          status: false,
        };
      });
      goodsList.push(newObj);
    });

    return goodsList;
  };

  // 保存
  handleSubmit = () => {
    const {
      location: { query: { id } },
    } = this.props;
    const { dataBaseList } = this.state;
    const saveData: any[] = [];
    let saveTrue = true;

    dataBaseList.forEach((item: any) => {
      Object.keys(item).forEach((i: any) => {
        if (!(!item[i].name && !item[i].layers && !item[i].status)) {
          saveData.push({
            code: i,
            ...item[i],
          });
        }
      });
    });

    saveData.forEach((item: any) => {
      if (!saveTrue) return;

      if (!(item.name && item.layers && item.status)) {
        Modal.error({
          title: `货架${item.code}填写信息不完整，请修改!`,
        });
        saveTrue = false;
      }

      item.layers = Number(item.layers);
      item.tariffpkgId = Number(item.tariffpkgId || 0);
      if (item.id) item.id = Number(item.id);
    });

    if (!saveTrue) return;
    this.fetchAction('saveOrUpdate', {
      logisId: Number(id),
      info: saveData,
    });
  };

  // 切换页码
  onChange = (pageIndex: number, pageSize: any) => {
    this.setState({ pageIndex, pageSize });
  };

  // 取消货架的保存
  routerBack = () => {
    router.push('/basic/goodsManagement/list');
  };

  // 选中状态的变化
  changeValue = (e: any, item: any) => {
    const { index, idName, type } = item;
    const { dataBaseList, pageIndex, pageSize } = this.state;
    const dataIndex = (pageIndex - 1) * pageSize + index;

    if (type === 'status') {
      const { checked } = e.target;
      dataBaseList[dataIndex][idName][type] = checked;
    } else {
      dataBaseList[dataIndex][idName][type] = e;
    }
    this.setState({ dataBaseList });
  };

  // 弹出弹框
  clickValue = (e: any, itemObj: any) => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { index, idValue, name } = itemObj;
    this.setState({
      visible: true,
      selectItem: { index, idValue, name },
    });
  };

  // 编辑货架名称、套餐选择
  handleOk = () => {
    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      const {
        selectItem: { index, idValue, name },
        dataBaseList,
        pageIndex,
        pageSize,
      } = this.state;
      const dataIndex = (pageIndex - 1) * pageSize + index;

      dataBaseList[dataIndex][idValue][name] = fieldsValue[name];
      this.setState({
        visible: false,
        dataBaseList,
      });
    });
  };

  // 取消编辑
  handleCancel = () => this.setState({ visible: false });

  // 全选与反选
  changeRow = (e: any, index: number) => {
    const { dataBaseList, pageIndex, pageSize } = this.state;

    const dataIndex = (pageIndex - 1) * pageSize + index;
    const dataBaseListChild = dataBaseList[dataIndex];
    const { checked } = e.target;

    Object.keys(dataBaseListChild).forEach((key: any) => {
      dataBaseListChild[key].status = checked;
    });

    this.setState({ dataBaseList });
  };

  validateMode = (rule: any, value: any, callback: any) => {
    if (value && value.length > 16) {
      callback('货架地址最多输入16位');
    } else {
      callback();
    }
  };

  // 查找套餐id对应的套餐名称
  findTariffName = (id: any) => {
    let tariffpkgName = '';
    if (!id) {
      tariffpkgName = '无';
    } else {
      const { INITINFO: { tariffList } } = this.props;
      tariffpkgName = tariffList.find((item: any) => item.id === id).name;
    }

    return tariffpkgName;
  };

  // 渲染货架列表
  renderGoodsListElem = (itemChild: any, indexChild: number) => {
    const { pliesNumber } = this.state;
    const checkedLength = Object.keys(itemChild).reduce((origin: number, key: string) => {
      if (itemChild[key].status) {
        origin += 1;
      }
      return origin;
    }, 0);

    return (
      <div
        key={`row_${indexChild}`}
        style={{
          display: 'flex',
          width: '100%',
          background: indexChild % 2 === 0 ? 'rgba(127, 203, 248, 0.08)' : '',
        }}
        className="goodsInfo"
      >
        <Checkbox
          className={styles.rowContent}
          checked={checkedLength === 4}
          onChange={e => this.changeRow(e, indexChild)}
        >
          全选本行
        </Checkbox>

        <Row gutter={12} style={{ flex: 1 }} className="goodsContent">
          {Object.keys(itemChild).map((item: any) => (
            <Col md={6} sm={24} key={item}>
              <Row gutter={12}>
                <Col md={6} sm={24} className={styles.flex}>
                  <Checkbox
                    style={{ width: '50px' }}
                    checked={itemChild[item].status}
                    onChange={e => this.changeValue(e, {
                      index: indexChild,
                      idName: item,
                      type: 'status',
                    })
                    }
                  >
                    {item}
                  </Checkbox>
                </Col>
                <Col md={7} sm={24} className={styles.rowBorderL}>
                  <Tooltip title={itemChild[item].name}>
                    <Input
                      bordered={false}
                      value={itemChild[item].name}
                      placeholder="请输入货架地址"
                      className={styles.heightAuto}
                      onClick={e => this.clickValue(e, {
                        index: indexChild,
                        idValue: item,
                        name: 'name',
                      })
                      }
                    />
                  </Tooltip>
                </Col>
                <Col md={5} sm={24} className={styles.middleSpans}>
                  <Select
                    showSearch
                    bordered={false}
                    allowClear
                    placeholder="层数"
                    className={styles.heightAuto}
                    value={itemChild[item].layers || undefined}
                    onChange={e => this.changeValue(e, {
                      index: indexChild,
                      idName: item,
                      type: 'layers',
                    })
                    }
                  >
                    {pliesNumber.map((plies: any) => (
                      <Option value={plies} key={plies}>
                        {plies}
                      </Option>
                    ))}
                  </Select>
                </Col>
                <Col md={6} sm={24} className={styles.rowBorderR}>
                  <Tooltip
                    title={
                      itemChild[item].tariffpkgId === ''
                        ? ''
                        : this.findTariffName(itemChild[item].tariffpkgId)
                    }
                  >
                    <Input
                      bordered={false}
                      className={styles.heightAuto}
                      value={
                        itemChild[item].tariffpkgId === ''
                          ? ''
                          : this.findTariffName(itemChild[item].tariffpkgId)
                      }
                      placeholder="套餐"
                      onClick={e => this.clickValue(e, {
                        index: indexChild,
                        idValue: item,
                        name: 'tariffpkgId',
                      })
                      }
                    />
                  </Tooltip>
                </Col>
              </Row>
            </Col>
          ))}
        </Row>
      </div>
    );
  };

  // 渲染弹窗
  renderModalElem = () => {
    let content;
    const {
      selectItem: { index, idValue, name },
      visible,
      dataBaseList,
      pageIndex,
      pageSize,
    } = this.state;

    const {
      form: { getFieldDecorator },
      INITINFO: { tariffList },
    }: any = this.props;
    if (!idValue || !visible) return null;

    const dataIndex = (pageIndex - 1) * pageSize + index;
    const item = dataBaseList[dataIndex][idValue][name];

    if (name === 'name') {
      content = (
        <div>
          <Form.Item label="货架地址" colon={false} className={styles.goodsTitle}>
            {getFieldDecorator('name', {
              initialValue: item,
              rules: [{ validator: this.validateMode }],
            })(<Input allowClear autoComplete="off" placeholder="请输入货架地址" />)}
          </Form.Item>
        </div>
      );
    } else {
      content = (
        <Form.Item label="套餐选择" colon={false} className={styles.goodsTitle}>
          {getFieldDecorator('tariffpkgId', {
            initialValue: item || 0,
          })(
            <Select
              showSearch
              allowClear
              placeholder="请选择套餐"
              filterOption={(input: any, option: any) => option.props.children
                .toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              style={{ width: 200 }}
            >
              <Option value={0}>无</Option>
              {tariffList.map((tariff: any) => (
                <Option value={tariff.id} key={tariff.id}>
                  {tariff.name}
                </Option>
              ))}
            </Select>,
          )}
        </Form.Item>
      );
    }

    return (
      <Modal
        title={`${idValue}货架`}
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
      >
        <Form className="tableListForm">{content}</Form>
      </Modal>
    );
  };

  render() {
    const { pageIndex, dataBaseList, pageSize } = this.state;
    const showData = dataBaseList.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);

    return (
      <>
        <PageHeader />

        <Card
          bordered={false}
          className="searchForm"
          style={{ background: '#fff', paddingBottom: '30px' }}
        >
          <div className="flexFeView" style={{ marginBottom: '41px' }}>
            <Button
              type="primary"
              onClick={this.handleSubmit}
            >
              保存
            </Button>
            <Button
              className="marginL16"
              onClick={this.routerBack}
            >
              取消
            </Button>
          </div>

          <div style={{ display: 'flex' }}>
            <p style={{ width: '80px' }} />
            <Row gutter={12} style={{ flex: 1 }}>
              {[1, 2, 3, 4].map((item: number) => (
                <Col md={6} sm={24} key={item}>
                  <Row gutter={12}>
                    <Col md={6} sm={24} />
                    <Col md={7} sm={24} className={`${styles.titleStyle} ${styles.borderL}`}>
                      货架地址
                    </Col>
                    <Col md={5} sm={24} className={`${styles.titleStyle} ${styles.middleSpan}`}>
                      层数
                    </Col>
                    <Col md={6} sm={24} className={`${styles.titleStyle} ${styles.borderR}`}>
                      套餐选择
                    </Col>
                  </Row>
                </Col>
              ))}
            </Row>
          </div>

          {showData.map((item: any, index: number) => this.renderGoodsListElem(item, index))}

          <Pagination
            className={styles.paginatioTop}
            total={176}
            defaultPageSize={15}
            pageSizeOptions={['10', '15', '20']}
            onChange={this.onChange}
            showTotal={total => `共 ${total} 条数据`}
          />

          {this.renderModalElem()}
        </Card>
      </>
    );
  }
}

export default Form.create<GoodsProps>()(GoodsElement);
